package com.example.test;

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import com.example.test.FriLineActivity.TimeLineAdapter;
import com.example.test.model.AsyncDownHeadImageTask;
import com.example.test.model.AsyncDownStatusImageTask;
import com.example.test.model.Constants;
import com.example.test.model.HashDataProcessor;
import com.example.test.model.NetAPI;
import com.example.test.model.QQAPI;
import com.example.test.model.RennAPI;
import com.example.test.model.SinaAPI;
import com.example.test.model.SohuWeiboAPI;
import com.example.test.model.StatusTextProcess;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;


public class TopicActivity extends Activity {
	ListView lvTimeline=null;
	List<HashMap<String, String>> lArrTimeline = null;
	HashMap<String, List<Drawable>> mapImgList=new HashMap<String, List<Drawable>>();
	TimeLineAdapter adapter;
	Drawable [] drawables;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
	     super.onCreate(savedInstanceState);
	     setContentView(R.layout.activity_topic);
	     Bundle bundle =getIntent().getExtras();
	     String title =bundle.getString("title");
	     String resource = bundle.getString("resource");
	     TextView tvTopic = (TextView)findViewById(R.id.tvTopicName);
	     tvTopic.setText(title);
	    	 QQAPI.getTopicTimeLine(this, null, title, handler);
	    	 
	}

	 Handler handler=new Handler()
		{

			@SuppressWarnings("unchecked")
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				if(msg.what==Constants.MSG_DOWNIMG_SUCCESS)
				{
					HashMap<String, Object> map=(HashMap<String, Object>)msg.obj;
					Integer position=(Integer)map.get("position");
					lArrTimeline.get(position).put("hasImg", "1");
					drawables[position]=(Drawable)map.get("img");
					adapter.notifyDataSetChanged();
				}
				else if(msg.what==Constants.MSG_GETTIMELINE_SUCCESS)
				{
					if(lArrTimeline==null)
					{
					HashDataProcessor.timelineDataProcess((List<HashMap<String,String>>)msg.obj);
					List<HashMap<String,String>> tempList =(List<HashMap<String,String>>)msg.obj;
					startDownStatusImg(tempList);
					lArrTimeline=tempList;
					}
					else
					{
						HashDataProcessor.timelineDataProcess((List<HashMap<String,String>>)msg.obj);
						startDownStatusImg((List<HashMap<String,String>>)msg.obj);
					lArrTimeline.addAll((List<HashMap<String,String>>)msg.obj);
					}
					lvTimeline=(ListView)findViewById(R.id.lvTimeline);
					Collections.sort(lArrTimeline,new StatusListComparator());
					drawables=new Drawable[lArrTimeline.size() ];
					adapter=new TimeLineAdapter(TopicActivity.this,handler, lArrTimeline,drawables);
			        lvTimeline.setAdapter(adapter);
			       for(int i=0;i<lArrTimeline.size();i++)
			       {
			       Thread thread=new Thread(new AsyncDownHeadImageTask(handler, i, lArrTimeline.get(i).get("userprofile_image_url")));
			       thread.start();
			       }
				}
				else if(msg.what==Constants.MSG_REPOST_SUCCESS)
				{
					Toast.makeText(TopicActivity.this, "转发成功", 1000).show();
				}
				else if(msg.what==Constants.MSG_REPOST_FAIL)
				{
					Toast.makeText(TopicActivity.this, "转发失败:"+msg.obj, 1000).show();
				}
				else if(msg.what==Constants.MSG_COMMENT_SUCCESS)
				{
					Toast.makeText(TopicActivity.this, "评论成功", 1000).show();
				}
				else if(msg.what==Constants.MSG_COMMENT_FAIL)
				{
					Toast.makeText(TopicActivity.this, "评论失败:"+msg.obj, 1000).show();
				}
				else if(msg.what==Constants.MSG_DOWNSTATUSIMG_SUCCESS)
				{
					HashMap<String, Object> map=(HashMap<String, Object>)msg.obj;
					String id=(String)map.get("id");
					String [] temp=id.split("_");
					mapImgList.get(temp[0]+"_"+temp[1]).set(Integer.parseInt(temp[2]), (Drawable)map.get("img"));
					adapter.notifyDataSetChanged();
				}
			}
			
		};
		
		 private void startDownStatusImg(List<HashMap<String,String>> tempList)
		 {
			 int i=0;
				for (HashMap<String, String> hashMap : tempList) {
					String id=tempList.get(i).get("resource")+"_"+tempList.get(i).get("id");
					List<Drawable> imgList=new LinkedList<Drawable>();
				String images=hashMap.get("images");
					if(!images.equals(""))
					{
						String []arrUrl=images.split(",");
						
						int j=0;
						for (String string : arrUrl) {
							Drawable drawable=null;
							imgList.add(drawable);
				Thread thread=new Thread(new AsyncDownStatusImageTask(handler, id+"_"+j,string));
				thread.start();
							j++;
						}
						
						
					}
					
					mapImgList.put(id, imgList);
					i++;
				}
		 }
		
		
		//内部类
		 class TimeLineAdapter extends BaseAdapter
		 {
		  Context context;
		  List<HashMap<String, String>> lsHashData;
		  Drawable []drawables;
		  Handler handler;
		  public TimeLineAdapter(Context context,Handler handler,List<HashMap<String, String>> data,Drawable []drawables)
		  {
			  this.handler=handler;
			  this.context=context;
			  this.drawables=drawables;
			  this.lsHashData=data;
		  }
			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return lsHashData.size();
			}

			@Override
			public Object getItem(int arg0) {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public long getItemId(int arg0) {
				// TODO Auto-generated method stub
				return 0;
			}

			@SuppressLint({ "NewApi", "InlinedApi" })
			@Override
			public View getView(final int position, View convertView, ViewGroup parent) {
				{
					Log.v("count", position+"");
					if(convertView==null)
					{
			      	convertView=LayoutInflater.from(context).inflate
					    (R.layout.statusitem,null);
					}
					LinearLayout llUser =(LinearLayout)convertView.findViewById(R.id.lluser);
				TextView tvUsername=(TextView)convertView.findViewById(R.id.tvusername);
				TextView tvcretime=(TextView)convertView.findViewById(R.id.tvcretime);
				TextView tvsource=(TextView)convertView.findViewById(R.id.tvsource);
				final TextView tvstatusattitude=(TextView)convertView.findViewById(R.id.tvstatusattitude);
				TextView tvstatuscomment=(TextView)convertView.findViewById(R.id.tvstatuscomment);
				TextView tvstatusreposts=(TextView)convertView.findViewById(R.id.tvstatusreposts);
				TextView tvstatustext=(TextView)convertView.findViewById(R.id.tvstatustext);
				TextView tvretstatustext=(TextView)convertView.findViewById(R.id.tvretstatustext);
				
				String tid=((String)lsHashData.get(position).get("resource"))+"_"+((String)lsHashData.get(position).get("id"));
			    List<Drawable> tempList = mapImgList.get(tid);

				TableLayout tableLayout =(TableLayout)convertView.findViewById(R.id.tlPics);
				tableLayout.removeAllViews();
			    if(tempList.size()>0)
				{
			    	WindowManager wm = ((Activity)context).getWindowManager();
			    	int width = wm.getDefaultDisplay().getWidth();
			    	
					TableRow row=null;
			    for(int i=0;i<tempList.size();i++)
				{
			    	if(i%3==0)
			    	{
			    		row=new TableRow(context);
			    		row.setGravity(Gravity.CENTER);
			    	}
			    	
					ImageView view = new ImageView(context);
					if(tempList.get(i)!=null)
					{
						
					Drawable zoomDrawable=ModifyDrawableScale.zoomDrawable(tempList.get(i), ModifyDrawableScale.dip2px(context, width/3));
					view.setImageDrawable(zoomDrawable);
					
					}
					row.addView(view);
					if((i%3==2)||(i==tempList.size()-1))
					{
						if(i==tempList.size()-1&&i%3!=2)
						{
							for(int j=0;j<(2-(i%3));j++)
							{
								ImageView view1 = new ImageView(context);
								row.addView(view1);
							}
						}
						tableLayout.addView(row);
					}
				}
				}
			    
			    tableLayout.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						if(lsHashData.get(position).get("resource").equals("Renn"))
						{
							return;
						}
						Intent intent =new Intent(context,WeiBoDetailActivity.class);
						intent.putExtra("weiboID", lsHashData.get(position).get("id"));
						intent.putExtra("resource", lsHashData.get(position).get("resource"));
						context.startActivity(intent);
						
					}
				});
				if(lsHashData.get(position).get("resource").equals("QQ"))
				{
					ImageView ivResource=(ImageView)convertView.findViewById(R.id.ivResource); 
					ivResource.setImageResource(R.drawable.qq_icon);
				}
				else if(lsHashData.get(position).get("resource").equals("sina"))
				{
					ImageView ivResource=(ImageView)convertView.findViewById(R.id.ivResource); 
					ivResource.setImageResource(R.drawable.ic_com_sina_weibo_sdk_logo);
				}
				else if(lsHashData.get(position).get("resource").equals("Renn"))
				{
					ImageView ivResource=(ImageView)convertView.findViewById(R.id.ivResource); 
					ivResource.setImageResource(R.drawable.renren_logo);
				}
				else if(lsHashData.get(position).get("resource").equals("netease"))
				{
					ImageView ivResource=(ImageView)convertView.findViewById(R.id.ivResource); 
					ivResource.setImageResource(R.drawable.net_logo);
				}
				else if(lsHashData.get(position).get("resource").equals("sohu"))
				{
					ImageView ivResource=(ImageView)convertView.findViewById(R.id.ivResource); 
					ivResource.setImageResource(R.drawable.sohu_logo);
				}
				//new String[]{"created_at","userscreen_name","source","text","reposts_count","comments_count","attitudes_count","profile_image_url"},
				//new int[]{R.id.tvcretime,R.id.tvusername,R.id.tvsource,R.id.tvstatustext,R.id.tvstatusreposts,R.id.tvstatuscomment,R.id.tvstatusattitude,R.id.ivuserhead
				if(lsHashData.get(position).get("retweeted_statustext")!=null)
				{
					tvretstatustext.setVisibility(View.VISIBLE);
					String content =lsHashData.get(position).get("retweeted_statususerscreen_name")+":"+lsHashData.get(position).get("retweeted_statustext");
					tvretstatustext.setText(content);
					tvretstatustext.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							Intent intent =new Intent(context,WeiBoDetailActivity.class);
							intent.putExtra("weiboID", lsHashData.get(position).get("retweeted_statusid"));
							intent.putExtra("resource", lsHashData.get(position).get("resource"));
							context.startActivity(intent);
						}
					});
				}
				else
				{
					tvretstatustext.setVisibility(View.GONE);
				}
				tvUsername.setText(lsHashData.get(position).get("userscreen_name"));
				tvcretime.setText(lsHashData.get(position).get("created_at"));
				tvsource.setText(lsHashData.get(position).get("source"));
				StatusTextProcess.setText(context, tvstatustext,lsHashData.get(position).get("text"),lsHashData.get(position).get("id"),lsHashData.get(position).get("resource"));
				tvstatusreposts.setText(lsHashData.get(position).get("reposts_count"));
				tvstatuscomment.setText(lsHashData.get(position).get("comments_count"));
				tvstatusattitude.setText(lsHashData.get(position).get("attitudes_count"));
				llUser.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						if(lsHashData.get(position).get("resource").equals("Renn"))
						{
							return;
						}
						Intent intent=new Intent();
						intent.setClass(context, HomeActivity.class);
						intent.putExtra("activity_type", lsHashData.get(position).get("resource"));
						intent.putExtra("uid", lsHashData.get(position).get("userid"));
							
						    context.startActivity(intent);
					}
				});
				tvstatusattitude.setOnClickListener(new TextView.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						String attitude = tvstatusattitude.getText().toString();
						int sIndex=attitude.indexOf('（');
						int eIndex=attitude.indexOf('）');
						attitude=attitude.substring(sIndex+1,eIndex);
						attitude = Integer.parseInt(attitude)+1+"";
						attitude="赞（"+attitude+"）";
						tvstatusattitude.setText(attitude);
						
					}
				});
				tvstatuscomment.setOnClickListener(new TextView.OnClickListener() {

					
					@Override
					public void onClick(View arg0) {
						final View view=LayoutInflater.from(context).inflate
								(R.layout.dlg_comment,null );
						final AlertDialog dlg = new AlertDialog.Builder(((FriLineActivity)context).getParent()).create();
						dlg.setView(view);
						Button btComment=(Button)view.findViewById(R.id.btComment);
						btComment.setOnClickListener(new Button.OnClickListener() {
							
							@Override
							public void onClick(View v) {
								
								final EditText etContent=(EditText)view.findViewById(R.id.etCommentText);
								final CheckBox cbISRepost=(CheckBox)view.findViewById(R.id.cbIsRepost);
								String content =etContent.getText().toString() ;
								if(content.trim().equals(""))
								{
									Toast.makeText(context, "评论内容不能为空", 1000).show();
									return;
								}
								if(lsHashData.get(position).get("resource").equals("sina"))
								{
									if(cbISRepost.isChecked() )
							    	{
							    	SinaAPI.repost(handler ,Long.parseLong(lsHashData.get(position).get("id")), content, false);
								    }
								    SinaAPI.comment(handler, Long.parseLong(lsHashData.get(position).get("id")), content);
								}
								else if(lsHashData.get(position).get("resource").equals("QQ"))
								{
									if(cbISRepost.isChecked() )
							    	{
							    	QQAPI.repost(context ,lsHashData.get(position).get("id"), content,handler);
								    }
									else
									{
								     QQAPI.comment(context, lsHashData.get(position).get("id"), content,handler);
									}
								}
								else if(lsHashData.get(position).get("resource").equals("Renn"))
								{
									if(cbISRepost.isChecked() )
							    	{
										 RennAPI.comment(handler,content,Long.parseLong(lsHashData.get(position).get("id")));
							    	RennAPI.share(handler,content,Long.parseLong(lsHashData.get(position).get("id")));
								    }
									else
									{
								     RennAPI.comment(handler,content,Long.parseLong(lsHashData.get(position).get("id")));
									}
									}
								else if(lsHashData.get(position).get("resource").equals("netease"))
								{
									if(cbISRepost.isChecked())
								    {
										NetAPI.comment(content, lsHashData.get(position).get("id"), "1", handler);
								    }
									else
									{
										NetAPI.comment(content, lsHashData.get(position).get("id"), "0", handler);
									}
								}
								else if(lsHashData.get(position).get("resource").equals("sohu"))
								{
									if(cbISRepost.isChecked())
								    {
										SohuWeiboAPI.repost(content, lsHashData.get(position).get("id"), handler);
								    }
									SohuWeiboAPI.comment(content,  lsHashData.get(position).get("id"), handler);
								}
								dlg.dismiss();
							}
						});
		                Button btCancel=(Button)view.findViewById(R.id.btCancel);
						
						btCancel.setOnClickListener(new Button.OnClickListener() {
							
							@Override
							public void onClick(View v) {
							dlg.cancel();
							}
						});
					    dlg.show();
					}
					
				}) ;

				
		        tvstatusreposts.setOnClickListener(new TextView.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Toast.makeText(context,  "the "+position+"th repost click",1000).show();
						View view=LayoutInflater.from(context).inflate
								(R.layout.dlg_repost,null );
						TextView tvSourceUser=(TextView)view.findViewById(R.id.tvsourceuser);
						final EditText etContent=(EditText)view.findViewById(R.id.etRepostText);
						final CheckBox cbISComment=(CheckBox)view.findViewById(R.id.cbIsComment);
						
						final AlertDialog dlg = new AlertDialog.Builder(((FriLineActivity)context).getParent()).create();
						dlg.setView(view);
						
						
						Button btRepost=(Button)view.findViewById(R.id.btRepost);
						
						btRepost.setOnClickListener(new Button.OnClickListener() {
							
							@Override
							public void onClick(View v) {
							String content =etContent.getText().toString() ;
							boolean isComment =cbISComment.isChecked();
							if(lsHashData.get(position).get("resource").equals("sina"))
							{
							SinaAPI.repost(handler ,Long.parseLong(lsHashData.get(position).get("id")), content, isComment);
							}
							else if(lsHashData.get(position).get("resource").equals("QQ"))
							{
								QQAPI.repost(context, lsHashData.get(position).get("id"), content,handler);
							}
							else if(lsHashData.get(position).get("resource").equals("Renn"))
							{
								RennAPI.share(handler, content, Long.parseLong(lsHashData.get(position).get("id")));
								if(isComment)
									RennAPI.comment(handler, content, Long.parseLong(lsHashData.get(position).get("id")));
							}
							else if(lsHashData.get(position).get("resource").equals("netease"))
							{
								if(isComment)
							    {
									NetAPI.repost(content, lsHashData.get(position).get("id"), "1", handler);
							    }
								else
								{
									NetAPI.repost(content, lsHashData.get(position).get("id"), "0", handler);
								}
							}
							else if(lsHashData.get(position).get("resource").equals("sohu"))
							{
								SohuWeiboAPI.repost(content, lsHashData.get(position).get("id"), handler);
								if(isComment)
							    {
									SohuWeiboAPI.comment(content, lsHashData.get(position).get("id"), handler);
							    }
							}
							dlg.cancel();
							}
						});
		                Button btCancel=(Button)view.findViewById(R.id.btCancel);
						
						btCancel.setOnClickListener(new Button.OnClickListener() {
							
							@Override
							public void onClick(View v) {
							dlg.cancel();
							}
						});
						dlg.show();
						tvSourceUser.setText(lsHashData.get(position).get("userscreen_name"));
						
					}
				});
				}
				
				if(lsHashData.get(position).get("hasImg")!=null)
				{
					ImageView ivUserHead =(ImageView) convertView.findViewById(R.id.ivuserhead);
					ivUserHead.setImageDrawable(drawables[position]);
				}
				else
				{
					ImageView ivUserHead =(ImageView) convertView.findViewById(R.id.ivuserhead);
					ivUserHead.setImageResource(R.drawable.nohead);
				}
				return convertView;
			}
			
		 }
		 
		 
}
